<script setup lang="ts">
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import { timeFormat, copyToCliboard } from '@/hooks/util'
import * as accountApi from '@/api/account'
import { message } from 'ant-design-vue'
import GroupList from './components/GroupList.vue'
import EditRemark from './components/EditRemark.vue'
import DelWxRobot from './components/DelWxRobot.vue'
import SetGroup from './components/SetGroup.vue'
import RechargeAuthorization from './components/RechargeAuthorization.vue'
import LdleFish from './LdleFish.vue'
import TransferDuration from './components/TransferDuration.vue'
import SearchDrawer from '@/components/search-drawer/Index.vue'

const route = useRoute()
const searchDrawerRef = ref()
const groupListRef = ref()
const editRemarkRef = ref()
const delWxRobotRef = ref()
const setGroupRef = ref()
const rechargeAuthorizationRef = ref()
const ldleFishRef = ref()
const TransferDurationRef = ref()
const activeKey = ref<string>('1')
let searchFlag = ref<boolean>(false)

interface Pagination {
  page: number
  pageSize: number
  total: number
  current?: number
  onChange: Function
  showSizeChanger: boolean
  showQuickJumper: boolean
}

const handlePageChange = (page: any, pageSize: any) => {
  // console.log(page, pageSize)
  pagination.value.pageSize = pageSize
  searchParams.value.pageSize = pageSize
}

const pagination = ref<Pagination>({
  page: 1,
  pageSize: 10,
  total: 0,
  onChange: handlePageChange,
  showSizeChanger: true,
  showQuickJumper: true,
})
let loading = ref<boolean>(false)

interface SearchParams {
  currentPage: number
  pageSize: number
  wechatId?: string | undefined
  nickName?: string | undefined
  remark?: string | undefined
  groupId?: string
  expireState?: string | number
  robotState?: string | number
  updateState?: string | number
  wechatState?: string | number
}
const searchParams = ref<SearchParams>({
  currentPage: pagination.value.page,
  pageSize: pagination.value.pageSize,
})

const dataSource = ref([])
const columns = [
  {
    title: '头像',
    key: 'avatar',
    width: 100,
    algin: 'center',
  },
  {
    title: '昵称/分组',
    key: 'wechatAccount',
    width: 200,
  },
  {
    title: '微信号/wxid',
    key: 'userName',
    width: 300,
  },
  {
    title: '备注/编号',
    key: 'groupId',
    width: 350,
  },
  {
    title: '微信/客户端状态',
    key: 'wechatState',
    width: 300,
  },
  {
    title: '创建/过期时间',
    key: 'createTime',
    width: 300,
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right',
  },
]
// 表格多选
const selectedRowKey = ref<Array<any>>([])
const selectedRow = ref<Array<object>>([])
const onSelectChange = (selectedRowKeys: any[], selectedRows: any[]) => {
  selectedRowKey.value = selectedRowKeys
  selectedRow.value = selectedRows
}

// 翻页
const changePage = (e: any) => {
  pagination.value.current = e.current
  pagination.value.pageSize = e.pageSize
  searchParams.value.currentPage = pagination.value.current as number
  getList()
}

const getList = async () => {
  loading.value = true
  try {
    let { state, data, message: msg } = await accountApi.getList(searchParams.value)
    if (state === 200) {
      data.list.forEach((item: { isRemarkShow: boolean }) => {
        item.isRemarkShow = false
      })
      dataSource.value = data.list
      pagination.value.total = Number(data.totalCount)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
}

const EditRemarkSet = async (record: any) => {
  record.isRemarkShow = true
}
// 状态数量统计
interface NumInfo {
  renewNum: number | string
  robotOnLineNum: number | string
  robotOffLineNum: number | string
  totality: number | string
  updateNum: number | string
  wechatRobotOffLineNum: number | string
  wechatRobotOnLineNum: number | string
}
const numInfo = ref<NumInfo>()
const getStatusNum = async () => {
  try {
    let { state, data, message: msg } = await accountApi.statisticalMagnitude()
    if (state === 200) {
      numInfo.value = data
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

onMounted(() => {
  getGroupList()
  getStatusNum()
})
const GetRowClassName = () => {
  return 'ant-table-cell-row-hover'
}

// 查询
const formRef = ref()
import type { SelectProps } from 'ant-design-vue'
const robotStateList = ref<SelectProps['options']>([
  {
    label: '正常',
    value: 1,
  },
  {
    label: '手动关闭',
    value: 0,
  },
  {
    label: '异常',
    value: -1,
  },
])

const expireStateList = ref<SelectProps['options']>([
  {
    label: '不需要续费',
    value: 0,
  },
  {
    label: '需要续费',
    value: 1,
  },
])

const updateStateList = ref<SelectProps['options']>([
  {
    label: '无需更新',
    value: 0,
  },
  {
    label: '需要更新',
    value: 1,
  },
])

const wechatStateList = ref<SelectProps['options']>([
  {
    label: '离线',
    value: 0,
  },
  {
    label: '在线',
    value: 1,
  },
])

const groupList = ref<SelectProps['options']>([])
const getGroupList = async () => {
  try {
    let { state, data, message: msg } = await accountApi.getWechatRobotGroupList()
    if (state === 200) {
      groupList.value = data
      getList()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
interface FormState {
  wechatId?: string | undefined
  nickName?: string | undefined
  remark?: string | undefined
  groupId?: string | undefined
  expireState?: string | number
  robotState?: string | number
  updateState?: string | number
  wechatState?: string | number
}
const formState = reactive<FormState>({})
const search = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  formRef.value.validate().then(() => {
    searchParams.value.wechatId = formState.wechatId || ''
    searchParams.value.nickName = formState.nickName || ''
    searchParams.value.remark = formState.remark || ''
    searchParams.value.groupId = formState.groupId || ''
    searchParams.value.expireState = formState.expireState
    searchParams.value.robotState = formState.robotState
    searchParams.value.updateState = formState.updateState
    searchParams.value.wechatState = formState.wechatState
    getList()
  })
}

// 重置
const reset = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1

  formRef.value.resetFields()
  Reflect.deleteProperty(searchParams.value, 'wechatId')
  Reflect.deleteProperty(searchParams.value, 'nickName')
  Reflect.deleteProperty(searchParams.value, 'remark')
  Reflect.deleteProperty(searchParams.value, 'groupId')
  Reflect.deleteProperty(searchParams.value, 'expireState')
  Reflect.deleteProperty(searchParams.value, 'robotState')
  Reflect.deleteProperty(searchParams.value, 'updateState')
  Reflect.deleteProperty(searchParams.value, 'wechatState')

  getList()
}

// 删除
const del = async (id: string) => {
  delWxRobotRef.value.showModal(id)
}

// 备注
const editRemark = (id: string, str: string) => {
  editRemarkRef.value.showModal(id, str)
}

const showGroupName = (id: string) => {
  return groupList.value?.find(item => item.id === id)?.groupName || '未分组'
}

// 分组管理
const showGroupList = () => {
  groupListRef.value.showModal()
}

const addGroup = async () => {
  setGroupRef.value.showModal(selectedRowKey.value)
}

// 备注提交 -
const handleRemark = async (record: any) => {
  record.isRemarkShow = false
  let params = {
    id: record.id,
    remark: record.remark,
  }
  try {
    const { state, message: msg } = await accountApi.editRemark(params)
    if (state === 200) {
      message.success('备注保存成功')
      getList()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 充值时长
const rechargeAuthorization = (id: string) => {
  rechargeAuthorizationRef.value.showModal(id, 'wx')
}

// 转移时长
const transferDuration = (id: string) => {
  TransferDurationRef.value.showModal('wx', id)
}

const advancedSearch = () => {
  searchDrawerRef.value.showDrawer()
}
</script>

<template>
  <page-container :title="route.meta.title">
    <a-card style="overflow-x: scroll">
      <a-tabs v-model:activeKey="activeKey" size="small">
        <a-tab-pane key="1" tab="闲鱼" force-render>
          <LdleFish ref="ldleFishRef"></LdleFish>
        </a-tab-pane>
        <a-tab-pane key="2" tab="微信">
          <div class="searchBox">
            <a-form ref="formRef" layout="inline" :model="formState" class="formClass">
              <a-form-item label="分组查询" name="groupId">
                <a-select
                  v-model:value="formState.groupId"
                  placeholder="请选择"
                  style="width: 200px"
                  allowClear
                >
                  <a-select-option v-for="(item, index) in groupList" :key="index" :value="item.id">
                    {{ item.groupName }}
                  </a-select-option>
                </a-select>
              </a-form-item>

              <a-form-item label="微信昵称" name="nickName">
                <a-input
                  v-model:value="formState.nickName"
                  placeholder="微信昵称"
                  style="width: 200px"
                />
              </a-form-item>

              <a-form-item label="软件状态" name="robotState">
                <a-select
                  v-model:value="formState.robotState"
                  placeholder="请选择"
                  style="width: 200px"
                  allowClear
                >
                  <a-select-option
                    v-for="(item, index) in robotStateList"
                    :key="index"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>

              <SearchDrawer ref="searchDrawerRef">
                <div>
                  <a-form-item label="分组查询" name="groupId">
                    <a-select
                      v-model:value="formState.groupId"
                      placeholder="请选择"
                      style="width: 250px"
                      allowClear
                    >
                      <a-select-option
                        v-for="(item, index) in groupList"
                        :key="index"
                        :value="item.id"
                      >
                        {{ item.groupName }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>

                  <a-form-item label="微信昵称" name="nickName">
                    <a-input
                      v-model:value="formState.nickName"
                      placeholder="微信昵称"
                      style="width: 250px"
                    />
                  </a-form-item>

                  <a-form-item label="软件状态" name="robotState">
                    <a-select
                      v-model:value="formState.robotState"
                      placeholder="请选择"
                      style="width: 250px"
                      allowClear
                    >
                      <a-select-option
                        v-for="(item, index) in robotStateList"
                        :key="index"
                        :value="item.value"
                      >
                        {{ item.label }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>

                  <a-form-item label="续费状态" v-show="searchFlag" name="expireState">
                    <a-select
                      v-model:value="formState.expireState"
                      placeholder="请选择"
                      style="width: 250px"
                      allowClear
                    >
                      <a-select-option
                        v-for="(item, index) in expireStateList"
                        :key="index"
                        :value="item.value"
                      >
                        {{ item.label }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>

                  <a-form-item label="软件更新" name="updateState">
                    <a-select
                      v-model:value="formState.updateState"
                      placeholder="请选择"
                      style="width: 250px"
                    >
                      <a-select-option
                        v-for="(item, index) in updateStateList"
                        :key="index"
                        :value="item.value"
                        allowClear
                      >
                        {{ item.label }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>

                  <a-form-item label="微信状态" v-show="searchFlag" name="wechatState">
                    <a-select
                      v-model:value="formState.wechatState"
                      placeholder="请选择"
                      style="width: 250px"
                      allowClear
                    >
                      <a-select-option
                        v-for="(item, index) in wechatStateList"
                        :key="index"
                        :value="item.value"
                      >
                        {{ item.label }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>

                  <a-form-item label="微信ID" name="wechatId">
                    <a-input
                      v-model:value="formState.wechatId"
                      placeholder="微信ID"
                      style="width: 250px"
                    />
                  </a-form-item>

                  <a-form-item label="备注" name="remark">
                    <a-input
                      v-model:value="formState.remark"
                      placeholder="备注"
                      style="width: 250px"
                    />
                  </a-form-item>

                  <a-form-item style="text-align: right">
                    <a-button type="primary" @click="search">搜索</a-button>
                    <a-button @click="reset" style="margin-left: 10px">重置</a-button>
                  </a-form-item>
                </div>
              </SearchDrawer>

              <!-- <a-form-item style="margin-left: -8px">
                <div
                  style="
                    display: flex;
                    align-items: center;
                    color: #1890ff;
                    justify-content: center;
                    margin-left: 8px;
                    cursor: pointer;
                  "
                  @click="() => (searchFlag = !searchFlag)"
                >
                  <div style="margin-top: 2px">{{ searchFlag ? '收起' : '展开' }}</div>
                  <UpOutlined
                    :style="{
                      transform: !searchFlag ? 'rotate(180deg)' : 'rotate(0)',
                      transition: '0.5s',
                      color: '#1890ff',
                      fontSize: '14px',
                      marginLeft: '8px',
                    }"
                  />
                </div>
              </a-form-item> -->

              <a-form-item>
                <a-button type="primary" @click="search">搜索</a-button>
                <a-button @click="reset">重置</a-button>
                <a-button type="primary" @click="advancedSearch">高级搜索</a-button>
              </a-form-item>
            </a-form>
          </div>

          <div style="margin: 5px 0">
            <a-button
              type="primary"
              style="border-radius: 6px; margin-right: 6px"
              @click="showGroupList"
            >
              分组管理
            </a-button>

            <!-- <a-button
              type="primary"
              style="border-radius: 6px; margin-left: 10px"
              @click="addGroup"
            >
              设置分组
            </a-button> -->
            <a-dropdown v-if="selectedRowKey.length > 0">
              <a-button style="margin-left: 10px;">
                批量操作
                <DownOutlined />
              </a-button>
              <template #overlay>
                <a-menu>
                  <a-menu-item @click="addGroup">设置分组</a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </div>

          <a-alert
            description="小提示：只要鼠标在表格上，按住左Shift键并滚动鼠标滚轮就可以横向滚动表格"
            type="info"
            banner
            style="margin-bottom: 10px; padding: 10px"
          />

          <a-table
            style="overflow-x: scroll"
            :columns="columns"
            class="ant-table-striped"
            :scroll="{ x: 100 }"
            :data-source="dataSource"
            :pagination="pagination"
            :loading="loading"
            @change="changePage"
            rowKey="id"
            :row-selection="{ selectedRowKeys: selectedRowKey, onChange: onSelectChange }"
            :rowClassName="GetRowClassName"
            size="small"
          >
            <template #emptyText>
              <a-empty description=" 暂无数据" />
            </template>

            <template #headerCell="{ column }">
              <template v-if="column.key === 'id'">
                <span>id</span>
              </template>

              <template v-if="column.key === 'avatar'">
                <div style="text-align: center">
                  <span>头像</span>
                </div>
              </template>
            </template>

            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'wechatAccount'">
                <a-descriptions bordered size="small" :column="1">
                  <a-descriptions-item label="昵称">
                    {{ record.nickName }}
                    <a @click="copyToCliboard(record.nickName)"><CopyOutlined /></a>
                  </a-descriptions-item>
                  <a-descriptions-item label="分组">
                    {{ showGroupName(record.groupId) }}
                  </a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-else-if="column.key === 'avatar'">
                <div class="imgBox">
                  <img :src="record.avatar" alt="" />
                </div>
              </template>

              <template v-else-if="column.key === 'createTime'">
                <a-descriptions bordered size="small" :column="1">
                  <a-descriptions-item label="创建时间">
                    {{ timeFormat(record.createTime) }}
                  </a-descriptions-item>
                  <a-descriptions-item label="过期时间">
                    {{ timeFormat(record.expireTime) }}
                  </a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-else-if="column.key === 'userName'">
                <a-descriptions bordered size="small" :column="1">
                  <a-descriptions-item label="微信号">
                    {{ record.wechatAccount }}
                  </a-descriptions-item>
                  <a-descriptions-item label="微信ID">
                    {{ record.wechatId }}
                    <a @click="copyToCliboard(record.wechatId)"><CopyOutlined /></a>
                  </a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-else-if="column.key === 'groupId'">
                <a-descriptions bordered size="small" :column="1">
                  <a-descriptions-item label="备注">
                    <div style="display: flex; align-items: center">
                      <a-tooltip placement="top" v-if="!record.isRemarkShow">
                        <template #title>
                          <span>{{ record.remark }}</span>
                        </template>
                        <span class="hiddenText">{{ record.remark }}</span>
                      </a-tooltip>
                      <a-input
                        v-else
                        v-model:value="record.remark"
                        @blur="handleRemark(record)"
                        style="border: 0"
                      />
                      <EditOutlined
                        @click="EditRemarkSet(record)"
                        v-if="!record.isRemarkShow"
                        style="margin-left: 6px; color: #1890ff"
                      />
                    </div>
                  </a-descriptions-item>
                  <a-descriptions-item label="编号">{{ record.id }}</a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-else-if="column.key === 'wechatState'">
                <a-descriptions bordered size="small" :column="1">
                  <a-descriptions-item label="微信">
                    <a-tag color="blue" v-if="record.wechatState == 1">正常</a-tag>
                    <a-tag color="red" v-else>离线</a-tag>
                  </a-descriptions-item>
                  <a-descriptions-item label="客户端状态">
                    <a-tag color="blue" v-if="record.robotState == 1">正常</a-tag>
                    <a-tag color="red" v-else-if="record.robotState == -1">异常</a-tag>
                    <a-tag color="red" v-else>手动关闭</a-tag>
                  </a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-else-if="column.key === 'action'">
                <div style="text-align: center; width: 100px">
                  <div style="margin: 0; padding: 0">
                    <a @click="rechargeAuthorization(record.id)">充值时长</a>
                  </div>
                  <div style="margin: 0; padding: 0">
                    <a style="color: #999">转移时长</a>
                  </div>
                  <div>
                    <a @click="transferDuration(record.id)">转移时长</a>
                  </div>
                </div>
              </template>
            </template>
          </a-table>

          <SetGroup ref="setGroupRef" @refresh="getList"></SetGroup>
          <DelWxRobot ref="delWxRobotRef" @refresh="getList"></DelWxRobot>
          <EditRemark ref="editRemarkRef" @refresh="getList"></EditRemark>
          <GroupList ref="groupListRef"></GroupList>
          <RechargeAuthorization
            ref="rechargeAuthorizationRef"
            @refresh="getList"
          ></RechargeAuthorization>
          <TransferDuration ref="TransferDurationRef" @refresh="getList"></TransferDuration>
        </a-tab-pane>
      </a-tabs>
    </a-card>
  </page-container>
</template>

<style lang="less" scoped>
.hiddenText {
  display: inline-block;
  max-width: 160px;
  overflow: hidden;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  line-height: 16px;
}

.formClass {
  :nth-child(1) {
    // margin-bottom: 2px;
  }
}

.searchBox {
  // margin-bottom: 10px;
  display: flex;

  input {
    // width: 200px;
    margin-right: 10px;
  }

  button {
    margin-right: 10px;
  }
}

a:hover {
  color: red;
}

.imgBox {
  width: 50px;
  height: 50px;
  margin: 0 auto;
  border-radius: 50%;
  overflow: hidden;

  img {
    height: 50px;
  }
}

:deep(.ant-table-cell) {
  padding: 0;
}

:deep(.ant-form-item-label) {
  width: 70px;
}
</style>
